package des.wangku.operate.standard.tools;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * 针对HttpServletRequest进行操作
 * 
 * @author Sunjian
 * @version 1.0
 * @since jdk1.8
 */
public final class HttpServletRequests {
	/**
	 * 得到key的多个值，适用于多个input输入
	 * @param request HttpServletRequest
	 * @param key String
	 * @return List&lt;String&gt;
	 */
	public static List<String> getParameterList(HttpServletRequest request, String key) {
		List<String> list = new ArrayList<>();
		if (request == null) return list;
		Enumeration<?> paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			if (!paramName.equals(key)) continue;
			String[] paramValues = request.getParameterValues(paramName);
			for(String e:paramValues) {
				list.add(e);
			}
			break;
		}
		return list;
	}

	/**
	 * 得到所有参数对的参数名 abc 如果有abc_title，则保存abc<br>
	 * 尾部词 _title
	 * @param request HttpServletRequest
	 * @param endkey String
	 * @return List&lt;String&gt;
	 */
	public static List<String> getParadigmNameList(HttpServletRequest request,String endkey) {
		Map<String, String> map = getRequestParameterMap(request);
		List<String> list = new ArrayList<String>();
		for (String key : map.keySet())
			if (map.containsKey(key + endkey)) list.add(key);
		return list;
	}

	/**
	 * 通过 HttpServletRequest 得到参数map 只允许一个值
	 * @param request HttpServletRequest
	 * @return Map&lt;String, String&gt;
	 */
	public static Map<String, String> getRequestParameterMap(HttpServletRequest request) {
		Map<String, String> map = new HashMap<>();
		Map<String, List<String>> allMap = requestParameterToMap(request);
		for (String key : allMap.keySet())
			map.put(key, allMap.get(key).get(0));
		return map;
	}

	/**
	 * 通过 HttpServletRequest 得到参数map 允许多个同名参数值用list保存
	 * @param request HttpServletRequest
	 * @return Map&lt;String, List&lt;String&gt;&gt;
	 */
	public static Map<String, List<String>> requestParameterToMap(HttpServletRequest request) {
		Map<String, List<String>> map = new HashMap<>();
		if (request == null) return map;
		Enumeration<?> paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			String[] paramValues = request.getParameterValues(paramName);
			if (paramValues.length == 0) continue;
			List<String> list = new ArrayList<>(paramValues.length);
			for(String e:paramValues) {
				list.add(e);
			}
			map.put(paramName, list);
		}
		return map;
	}

}
